package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.model.result.StarInfoResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.IPushExtHandleService;
import com.block.datapush.service.apipush.utils.JinChengUtil;
import com.block.datapush.service.apipush.utils.WenZhouUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 锦诚
 */
@Service
public class JinChengPushApiService implements IPushApiService, IPushExtHandleService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("tel", memberSourceInfo.getMobileMd5());


        log.info("【锦诚】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createGet(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【锦诚】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String resMsg = resultObject.getString("resMsg");

        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(resMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "1")) {
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();


        Map<String, Object> bizMap = new HashMap<>();
        String channelCode = memberSourceInfo.getChannelCode();
        if(StrUtil.equals(channelCode,"2LW530")){
            bizMap.put("channel_source", "臻享分期-银行");
        }else {
            bizMap.put("channel_source", "臻享分期");
        }
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("phone", memberSourceInfo.getMobile());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex());
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("loanAmount", JinChengUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("profession", JinChengUtil.getGongzuo(memberSourceInfo.getGongzuo()));
        bizMap.put("zhima", JinChengUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("providentFund", JinChengUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("socialSecurity", JinChengUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("house", JinChengUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("car", JinChengUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("education", JinChengUtil.getxueli(memberSourceInfo.getXueli()));
        bizMap.put("insurance", JinChengUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("overdue", JinChengUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("creditCard", memberSourceInfo.getXinyongka() == "xyk001" ? 1 : 2);
        bizMap.put("unitPrice", pushApiKeyParam.getApiCode());

        String datas = JSON.toJSONString(bizMap);
        String data = new AES(Mode.CBC, Padding.PKCS5Padding, pushApiKeyParam.getApiKey().getBytes(), pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(datas);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("sign", data);

        log.info("【锦诚】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【锦诚】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String resMsg = resultObject.getString("resMsg");

        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(resMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "1")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }


    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    @Override
    public StarInfoResult handleStarInfo(MerchantBaseInfo merchantBaseInfo, Map<String, String[]> parameterMap, String paramContent) throws Exception {
        StarInfoResult starInfoResult = new StarInfoResult();
        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);

        if (ObjectUtil.isEmpty(jsonObjectParamContent)) {
            return starInfoResult;
        }

        String mobileMd5 = jsonObjectParamContent.getString("mobileMd5");
        Integer startLevel = jsonObjectParamContent.getInteger("startLevel");
        starInfoResult.setMobileMd5(mobileMd5);
        starInfoResult.setStarLevel(startLevel);
        return starInfoResult;
    }
}
